//
//  BlackListViewController.m
//  AAIM
//
//  Created by 远的小布丁 on 2019/12/5.
//  Copyright © 2019 AAIM. All rights reserved.
//

#import "BlackListViewController.h"
#import "BlackListTableViewCell.h"
#import "EMChineseToPinyin.h"
#import "ContactModel.h"
#import "ContactRequestLogic.h"

@interface BlackListViewController ()<UITableViewDelegate,UITableViewDataSource,BlackListCellDelegate>
@property (nonatomic,strong)UITableView * blackListTableView;
@property (nonatomic, strong) NSMutableArray<NSString *> *sectionTitles;
@property (nonatomic, strong) NSMutableArray *dataSources;//黑名单列表数据
@property (nonatomic,assign) int num;//计数
@property (nonatomic,strong) UIButton *rightBtn;
@property (nonatomic,strong)NSMutableArray * indexAry;//用于保存已选的下标
@property (nonatomic,strong)NSMutableArray * listArr;
@property (nonatomic,strong)MJTableViewNullDataView * nullDataView;
@end

@implementation BlackListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"黑名单";
    _num = 0;
    _sectionTitles = [NSMutableArray array];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.gk_navLineHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    _indexAry = [NSMutableArray array];
    [self.view addSubview:self.blackListTableView];
    [self.blackListTableView addSubview:self.nullDataView];

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getBlackListData];
}

- (void)getBlackListData{
    [self.dataSources removeAllObjects];
    [self.sectionTitles removeAllObjects];
    [self.listArr removeAllObjects];
    [ContactRequestLogic requestBlackListSuccess:^(NSDictionary * _Nonnull Dict) {
        NSLog(@"m黑名单:%@",Dict);
         NSLog(@"黑名单结果:%@",Dict[@"message"]);
        KWeakSelf;
        for (NSDictionary * dataDic in Dict[@"data"]) {
            ContactModel * blackFriendModel = [ContactModel mj_objectWithKeyValues:dataDic];
            [self.listArr addObject:blackFriendModel];
        }
        if (weakSelf.listArr.count == 0) {
            weakSelf.nullDataView.hidden = NO;
        }
        [weakSelf sortAllContacts:weakSelf.listArr];
    } failure:^(NSString * _Nonnull errMsg) {
        [self showTipHudWithText:errMsg];
    }];
}

- (void)sortAllContacts:(NSArray *)aContactList
{
    [self.dataSources removeAllObjects];
    [self.sectionTitles removeAllObjects];
    
    NSMutableArray *contactArray = [NSMutableArray arrayWithArray:aContactList];
    
    //建立索引的核心, 返回27，是a－z和＃
    UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
    [self.sectionTitles addObjectsFromArray:[indexCollation sectionTitles]];
    
    NSInteger highSection = [self.sectionTitles count];
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:highSection];
    for (int i = 0; i < highSection; i++) {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sortedArray addObject:sectionArray];
    }
    
    //按首字母分组
    for (ContactModel *contact in contactArray) {
        NSString *firstLetter = [EMChineseToPinyin pinyinFromChineseString:contact.nickname];
        NSInteger section;
        if (firstLetter.length > 0) {
            section = [indexCollation sectionForObject:[firstLetter substringToIndex:1] collationStringSelector:@selector(uppercaseString)];
        } else {
            section = [sortedArray count] - 1;
        }
        
        NSMutableArray *array = [sortedArray objectAtIndex:section];
        [array addObject:contact];
    }
    
    //每个section内的数组排序
    for (int i = 0; i < [sortedArray count]; i++) {
        NSArray *array = [[sortedArray objectAtIndex:i] sortedArrayUsingComparator:^NSComparisonResult(ContactModel *contact1, ContactModel *contact2) {
            NSString *firstLetter1 = [EMChineseToPinyin pinyinFromChineseString:contact1.nickname];
            firstLetter1 = [[firstLetter1 substringToIndex:1] uppercaseString];
            
            NSString *firstLetter2 = [EMChineseToPinyin pinyinFromChineseString:contact2.nickname];
            firstLetter2 = [[firstLetter2 substringToIndex:1] uppercaseString];
            
            return [firstLetter1 caseInsensitiveCompare:firstLetter2];
        }];
        
        [sortedArray replaceObjectAtIndex:i withObject:[NSMutableArray arrayWithArray:array]];
    }
    
    //去掉空的section
    for (NSInteger i = [sortedArray count] - 1; i >= 0; i--) {
        NSArray *array = [sortedArray objectAtIndex:i];
        if ([array count] == 0) {
            [sortedArray removeObjectAtIndex:i];
            [self.sectionTitles removeObjectAtIndex:i];
        }
    }
    [self.dataSources addObjectsFromArray:sortedArray];
    [self.blackListTableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSources.count;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    ContactModel * model =self.dataSources[indexPath.section][indexPath.row];
//    FriendsInfoViewController* vc =[[FriendsInfoViewController alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSources[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BlackListTableViewCell *cell = [ tableView dequeueReusableCellWithIdentifier:[BlackListTableViewCell cellIdentifier] forIndexPath:indexPath];
    if (!cell) {
        cell = [[BlackListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[BlackListTableViewCell cellIdentifier]];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.contactor = self.dataSources[indexPath.section][indexPath.row];
    cell.indexPath_row = indexPath.row;
    cell.indexPath_sec = indexPath.section;
    cell.delegate = self;
    return cell;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.sectionTitles;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = kColor_LightGray;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, tableView.frame.size.width - 20, 20)];
    label.backgroundColor = kColor_LightGray;
    label.font = [UIFont systemFontOfSize:15];
    
    NSString *title = self.sectionTitles[section];
    label.text = [NSString stringWithFormat:@"  %@", title];
    [view addSubview:label];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (void)deleClick:(UIButton *)sender{
//  NSArray *result = [ valueForKeyPath:@"@distinctUnionOfObjects.self"];
//    NSMutableArray * seAry;
//    AAIMLog(@"选中的按钮-=%@",self.indexAry);
//    NSString * fuuids;
//    __block NSString * weakFuuid = fuuids;
//    //选中的模型
//    [self.indexAry enumerateObjectsUsingBlock:^(ContactModel* selectedobj, NSUInteger idx, BOOL * _Nonnull stop) {
//        //模型结构是二维的 第一层是区 第二层是数据模型 。遍历拿到对应区
//        [self.dataSources enumerateObjectsUsingBlock:^(NSMutableArray *sections, NSUInteger idx, BOOL * _Nonnull stop) {
//            //拿到每个区的模型
//              [sections enumerateObjectsUsingBlock:^(ContactModel  * obj, NSUInteger deleteidx, BOOL * _Nonnull stop) {
//                  //选中的模型对比区模型
//                if ([selectedobj.userName isEqualToString:obj.userName]) {
//                    if ([CommonTools isEmpty:fuuids]) {
//                        weakFuuid = obj.fuuid;
//                    }else{
//                        weakFuuid = [NSString stringWithFormat:@"%@,%@",fuuids,obj.fuuid];
//                    }
//                    [sections removeObjectAtIndex:deleteidx];
//                }
//            }];
//        }];
//
//    }];
//    [self deleteFriendBlackList:weakFuuid];
//    [_indexAry removeAllObjects];
//    _num = 0;
//    [_rightBtn setBackgroundColor:KHEXCOLOR(@"#D8D8D8")];
//    _rightBtn.userInteractionEnabled = NO;
//    [self getBlackListData];
//    NSLog(@"移除");
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return  32.f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 53.f;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //选中的模型
        
            //模型结构是二维的 第一层是区 第二层是数据模型 。遍历拿到对应区
            [self.dataSources enumerateObjectsUsingBlock:^(NSMutableArray *sections, NSUInteger idx, BOOL * _Nonnull stop) {
                //拿到每个区的模型
                [sections enumerateObjectsUsingBlock:^(ContactModel  * obj, NSUInteger deleteidx, BOOL * _Nonnull stop) {
                    //选中的模型对比区模型
                    
                    if (indexPath.row == deleteidx) {
                        [self deleteFriendBlackList:obj.fuuid];
                        [sections removeObjectAtIndex:deleteidx];
                    }
                }];
            }];
    }
    [self getBlackListData];

}


// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"移除黑名单";
}


-(void)changeRightBtnStatus:(UIButton *)sender{
    BlackListTableViewCell *cell = (BlackListTableViewCell *)[[sender superview] superview];
    // 获取cell的indexPath
//    NSIndexPath *indexPath = [self.blackListTableView indexPathForCell:cell];
    if (sender.selected) {
        _num++;

    }else{
        _num--;

    }
    
    if (_num == 0) {

        [_rightBtn setBackgroundColor:KHEXCOLOR(@"#D8D8D8")];
        _rightBtn.userInteractionEnabled = NO;
    }else{

        [_rightBtn setBackgroundColor:KHEXCOLOR(@"#4795EF")];
        _rightBtn.userInteractionEnabled = YES;

    }
    
    ContactModel * model = self.dataSources[cell.indexPath_sec][cell.indexPath_row];
    if (cell.statuBtn.selected) {
        model.seleoctedState=YES;
        [self.indexAry addObject:model];
    }else
    {
        model.seleoctedState=NO;
        [self.indexAry removeObject:model];
    }
    
    [self.blackListTableView reloadData];
    

//    NSLog(@"点击的是第%ld行按钮",indexPath.row);
//    NSLog(@"%d",_num);
//    NSLog(@"%@",_indexAry);
   
}

- (void)deleteFriendBlackList:(NSString *)fuuids{

    [ContactRequestLogic requestJoinBlackListFriendWithFuuid:fuuids withBlock:@"0" withDescribe:@"" withRemark:@"" Success:^(NSDictionary * _Nonnull Dict) {
        NSLog(@"%@",Dict);
        [[UserDataBaseTool shareUserDataBaseTool] reloadData:1 Success:^(BOOL isOK) {
            if (isOK) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemAddFriends object:nil];
            }
        }];
        [self showTipHudWithText:Dict[@"message"]];
    } failure:^(NSString * _Nonnull errMsg) {
      [self showTipHudWithText:errMsg];
    }];
}

- (UITableView *)blackListTableView{
    if (!_blackListTableView) {
        _blackListTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.gk_navigationBar.bottom, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
        _blackListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _blackListTableView.delegate = self;
        _blackListTableView.dataSource = self;
        _blackListTableView.backgroundColor = KHEXCOLOR(@"#FFFFFF");
         [_blackListTableView registerNib:[BlackListTableViewCell registerNib] forCellReuseIdentifier:[BlackListTableViewCell cellIdentifier]];
//        UIView * searchBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40.f)];
//        searchBackView.backgroundColor = [UIColor whiteColor];
//        _blackListTableView.tableHeaderView = searchBackView;
//
//        AwSearch * searchView = [[AwSearch alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 32.f)];
//        searchView.isFirstResponser = NO;
//        // 是否展示右侧btn
//        searchView.isShowRightBtn = NO;
        // 设置icon
        // 图片
//        searchView.iconName = @"搜索"; //search_icon_white search_icon
        // icon大小
//        searchView.iconSize = CGSizeMake(15, 15);
        // icon 位置
        //    searchView.insetsIcon = UIEdgeInsetsMake(0, 30, 0, 0);
        
        // 设置placehodler
//        searchView.placeHolder = @"搜索";
        /// placeholder 颜色
//            searchView.colorPlaceholder = KHEXCOLOR(@"#D8D8D8");
        /// placeholder 字体大小
//        searchView.cusFontPlaceHolder = 13;
        
        //设置搜索框背景色
//            searchView.colorSearchBg = KHEXCOLOR(@"#F5F5F5");
//        /// 圆角
//            searchView.raidus = 5;
        /// 设置灰色背景边距
        //    searchView.insetsSearchBg = UIEdgeInsetsMake(0, 0, 0, 0);
        
        /// 设置txtfield边距 左侧距离icon 其他距离灰色背景
        //    searchView.insetsTxtfield = UIEdgeInsetsMake(10, 10, 20, 50);
        // textfield 字体大小
        //    searchView.cusFontTxt = 20;
        // textfield 字体颜色
        //    searchView.colorTxtInput = [UIColor redColor];
        
        /// 按钮设置
        // 标题
//        searchView.titleBtn = @"确定";
        /// 颜色
        //    searchView.colorTitleBtn = [UIColor redColor];
        
        /// 按钮图片
        //    searchView.imgBtn = @"search_icon_white";
        /// 按钮背景图片
        //    searchView.imgBtnBg = @"search_icon";
        /// 按钮背景色
        //    searchView.colorBtnBg = [UIColor redColor];
        /// 按钮边距
        //    searchView.insetsBtn = UIEdgeInsetsMake(5, 10, 10, 20);
//        [searchView setTxtfieldEditingCallback:^(NSString *text) {
//
//        }];
//
//        [searchView setKeyboardHideCallback:^{
//            NSLog(@"ssss");
//        }];
//
//        [searchView setTouchSearchTextCallabck:^{
//            NSLog(@"aaaa");
//        }];
//        [searchBackView addSubview:searchView];
        
    }
    return _blackListTableView;
}

- (NSMutableArray *)dataSources {
    if (!_dataSources) {
        _dataSources = [NSMutableArray new];
    }
    return _dataSources;
}

- (NSMutableArray *)listArr{
    if (!_listArr) {
        _listArr = [NSMutableArray array];
    }
    return _listArr;
}

-(MJTableViewNullDataView*)nullDataView {
    if (!_nullDataView) {
        _nullDataView=[[MJTableViewNullDataView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, self.blackListTableView.frame.size.height-60)];
        _nullDataView.hidden=YES;
        _nullDataView.backgroundColor=KHEXCOLOR(@"#FFFFFF");
    }
    [_nullDataView setCustomViewFrame:@"空状态" message:@"暂时没有数据哦"];
    return _nullDataView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
